package com.dzx.swing;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author dzx
 * @ClassName:
 * @Description:
 * @date 2019年07月29日 11:41:57
 */
public class JFileChooserDemo {
    private JLabel label = new JLabel("所选文件路径：");
    private JTextField jtf = new JTextField(25);
    private JButton button = new JButton("浏览");

    public JFileChooserDemo() {
        JFrame jFrame = new JFrame();
        JPanel jPanel = new JPanel();

        jPanel.add(label);
        jPanel.add(jtf);
        jPanel.add(button);
        jFrame.add(jPanel);
        jFrame.pack();    //自动调整大小
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(new MyActionListener());    //监听按钮事件
    }

    private class MyActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser jFileChooser = new JFileChooser("F:\\");
            int i = jFileChooser.showOpenDialog(null);
            if (i == jFileChooser.APPROVE_OPTION) {
                jtf.setText(jFileChooser.getSelectedFile().toString());
            } else {
                //未正常选择文件，如选择取消按钮
                jtf.setText("未选择文件");
            }
        }
    }

    public static void main(String[] args) {
        new JFileChooserDemo();
    }
}
